package com.lsl.rdf.distributedLock.impl;

import com.lsl.rdf.distributedLock.DistributedLock;
import com.lsl.rdf.lock.AcquireDistributedLockException;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

/**
 * Created by lsl on 2021/4/26.
 */
@Slf4j
public class DistributedLockImpl implements DistributedLock {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public boolean acquireLock(String lockName, int waitSeconds, int overtimeSeconds) {
        RLock rLock = redissonClient.getLock(lockName);

        try {
            return rLock.tryLock(waitSeconds, overtimeSeconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("acquireLock 获取锁异常！lockName: {}", lockName, e);
            throw new AcquireDistributedLockException(e);
        }
    }

    @Override
    public boolean acquireFairLock(String lockName, int waitSeconds, int overtimeSeconds) {
        RLock fairLock = redissonClient.getFairLock(lockName);

        try {
            return fairLock.tryLock(waitSeconds, overtimeSeconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("acquireFairLock 获取公平锁异常！lockName: {}", lockName, e);
            throw new AcquireDistributedLockException(e);
        }
    }

    @Override
    public void releaseLock(String lockName) {
        RLock lock = redissonClient.getLock(lockName);
        if (lock.isLocked()) {
            lock.unlock();
        }
    }

    @Override
    public void releaseFairLock(String lockName) {
        RLock lock = redissonClient.getFairLock(lockName);
        if (lock.isLocked()) {
            lock.unlock();
        }
    }
}
